<template>
  <div class="game-mode">
    <div class="header">
      <button class="back-btn" @click="goBack">← 返回首页</button>
      <h1>游戏模式</h1>
      <div class="game-stats">
        <span class="score">得分: {{ score }}</span>
        <span class="level">关卡: {{ level }}</span>
        <span class="time">时间: {{ formatTime(timeLeft) }}</span>
        <span class="gamepad-status" :class="{ connected: gamepadConnected }">
          🎮 {{ gamepadConnected ? '手柄已连接' : '手柄未连接' }}
        </span>
      </div>
    </div>
    
    <div class="game-container">
      <div class="game-area">
        <div class="mission-panel">
          <h2>当前任务</h2>
          <div class="mission-info">
            <p class="mission-title">{{ currentMission.title }}</p>
            <p class="mission-desc">{{ currentMission.description }}</p>
            <div class="mission-progress">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: missionProgress + '%' }"></div>
              </div>
              <span class="progress-text">{{ missionProgress }}%</span>
            </div>
          </div>
        </div>
        
        <div class="game-map">
          <div class="map-container">
            <div class="vehicle" :style="vehicleStyle">🚗</div>
            <div v-for="(target, index) in targets" :key="index" 
                 class="target" :style="getTargetStyle(target)"
                 :class="{ collected: target.collected }">🎯</div>
            <div v-for="(obstacle, index) in obstacles" :key="index" 
                 class="obstacle" :style="getObstacleStyle(obstacle)">🚧</div>
          </div>
        </div>
        
        <div class="control-panel">
          <h2>控制面板</h2>
          
          <!-- Gamepad控制说明 -->
          <div class="gamepad-controls" v-if="gamepadConnected">
            <h3>🎮 手柄控制</h3>
            <div class="gamepad-instructions">
              <div class="instruction-row">
                <span class="control-key">左摇杆/方向键</span>
                <span class="control-desc">移动小车</span>
              </div>
              <div class="instruction-row">
                <span class="control-key">A按钮</span>
                <span class="control-desc">开始/暂停游戏</span>
              </div>
              <div class="instruction-row">
                <span class="control-key">B按钮</span>
                <span class="control-desc">停止移动</span>
              </div>
              <div class="instruction-row">
                <span class="control-key">X按钮</span>
                <span class="control-desc">重新开始</span>
              </div>
              <div class="instruction-row">
                <span class="control-key">Y按钮</span>
                <span class="control-desc">返回首页</span>
              </div>
            </div>
          </div>
          
          <div class="controls">
            <div class="direction-controls">
              <button class="control-btn" @click="move('forward')" :disabled="gameOver">↑</button>
              <div class="horizontal-controls">
                <button class="control-btn" @click="move('left')" :disabled="gameOver">←</button>
                <button class="control-btn stop" @click="stop()" :disabled="gameOver">停</button>
                <button class="control-btn" @click="move('right')" :disabled="gameOver">→</button>
              </div>
              <button class="control-btn" @click="move('backward')" :disabled="gameOver">↓</button>
            </div>
          </div>
          
          <div class="game-actions">
            <button class="action-btn start" @click="startGame" v-if="!gameStarted">开始游戏</button>
            <button class="action-btn pause" @click="pauseGame" v-if="gameStarted && !gamePaused">暂停</button>
            <button class="action-btn resume" @click="resumeGame" v-if="gameStarted && gamePaused">继续</button>
            <button class="action-btn restart" @click="restartGame" v-if="gameOver">重新开始</button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="game-overlay" v-if="gameOver">
      <div class="game-over-panel">
        <h2>游戏结束</h2>
        <p class="final-score">最终得分: {{ score }}</p>
        <p class="final-level">完成关卡: {{ level - 1 }}</p>
        <button class="restart-btn" @click="restartGame">重新开始</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GameMode',
  data() {
    return {
      score: 0,
      level: 1,
      timeLeft: 60,
      gameStarted: false,
      gamePaused: false,
      gameOver: false,
      missionProgress: 0,
      vehicle: { x: 50, y: 50 },
      targets: [],
      obstacles: [],
      gameTimer: null,
      currentMission: {
        title: '收集目标',
        description: '在时间限制内收集所有目标点，避开障碍物'
      },
      // Gamepad控制相关
      gamepadConnected: false,
      gamepadIndex: null,
      gamepadAnimationFrame: null,
      lastButtonStates: {},
      deadZone: 0.2 // 摇杆死区
    }
  },
  computed: {
    vehicleStyle() {
      return {
        left: this.vehicle.x + '%',
        top: this.vehicle.y + '%'
      }
    }
  },
  methods: {
    goBack() {
      this.stopGame()
      this.$router.push('/')
    },
    startGame() {
      this.gameStarted = true
      this.gameOver = false
      this.initializeLevel()
      this.startTimer()
    },
    pauseGame() {
      this.gamePaused = true
      this.stopTimer()
    },
    resumeGame() {
      this.gamePaused = false
      this.startTimer()
    },
    restartGame() {
      this.score = 0
      this.level = 1
      this.timeLeft = 60
      this.gameOver = false
      this.gamePaused = false
      this.missionProgress = 0
      this.vehicle = { x: 50, y: 50 }
      this.startGame()
    },
    stopGame() {
      this.gameStarted = false
      this.stopTimer()
    },
    initializeLevel() {
      this.targets = []
      this.obstacles = []
      
      // 生成目标点
      for (let i = 0; i < 3 + this.level; i++) {
        this.targets.push({
          x: Math.random() * 80 + 10,
          y: Math.random() * 80 + 10,
          collected: false
        })
      }
      
      // 生成障碍物
      for (let i = 0; i < this.level; i++) {
        this.obstacles.push({
          x: Math.random() * 80 + 10,
          y: Math.random() * 80 + 10
        })
      }
      
      this.updateMissionProgress()
    },
    move(direction) {
      if (this.gameOver || this.gamePaused) return
      
      const step = 5
      let newX = this.vehicle.x
      let newY = this.vehicle.y
      
      switch (direction) {
        case 'forward':
          newY = Math.max(0, this.vehicle.y - step)
          break
        case 'backward':
          newY = Math.min(90, this.vehicle.y + step)
          break
        case 'left':
          newX = Math.max(0, this.vehicle.x - step)
          break
        case 'right':
          newX = Math.min(90, this.vehicle.x + step)
          break
      }
      
      // 检查碰撞
      if (this.checkCollision(newX, newY)) {
        this.gameOver = true
        this.stopTimer()
        return
      }
      
      this.vehicle.x = newX
      this.vehicle.y = newY
      
      // 检查目标收集
      this.checkTargetCollection()
    },
    stop() {
      // 停止移动，不需要特殊处理
    },
    checkCollision(x, y) {
      return this.obstacles.some(obstacle => {
        const distance = Math.sqrt(
          Math.pow(x - obstacle.x, 2) + Math.pow(y - obstacle.y, 2)
        )
        return distance < 8
      })
    },
    checkTargetCollection() {
      this.targets.forEach(target => {
        if (!target.collected) {
          const distance = Math.sqrt(
            Math.pow(this.vehicle.x - target.x, 2) + 
            Math.pow(this.vehicle.y - target.y, 2)
          )
          if (distance < 8) {
            target.collected = true
            this.score += 100
            this.updateMissionProgress()
          }
        }
      })
      
      // 检查是否完成关卡
      if (this.targets.every(target => target.collected)) {
        this.level++
        this.timeLeft += 30
        this.initializeLevel()
      }
    },
    updateMissionProgress() {
      const collected = this.targets.filter(t => t.collected).length
      this.missionProgress = Math.round((collected / this.targets.length) * 100)
    },
    getTargetStyle(target) {
      return {
        left: target.x + '%',
        top: target.y + '%',
        opacity: target.collected ? 0.3 : 1
      }
    },
    getObstacleStyle(obstacle) {
      return {
        left: obstacle.x + '%',
        top: obstacle.y + '%'
      }
    },
    startTimer() {
      this.gameTimer = setInterval(() => {
        this.timeLeft--
        if (this.timeLeft <= 0) {
          this.gameOver = true
          this.stopTimer()
        }
      }, 1000)
    },
    stopTimer() {
      if (this.gameTimer) {
        clearInterval(this.gameTimer)
        this.gameTimer = null
      }
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins}:${secs.toString().padStart(2, '0')}`
    },
    
    // Gamepad控制方法
    initGamepad() {
      // 检查浏览器是否支持Gamepad API
      if (!navigator.getGamepads) {
        console.warn('此浏览器不支持Gamepad API')
        return
      }
      
      // 监听gamepad连接事件
      window.addEventListener('gamepadconnected', this.onGamepadConnected)
      window.addEventListener('gamepaddisconnected', this.onGamepadDisconnected)
      
      // 检查是否已有连接的gamepad
      this.checkExistingGamepads()
      
      console.log('Gamepad系统已初始化')
    },
    
    checkExistingGamepads() {
      const gamepads = navigator.getGamepads()
      for (let i = 0; i < gamepads.length; i++) {
        if (gamepads[i]) {
          this.connectGamepad(i)
          break
        }
      }
    },
    
    onGamepadConnected(event) {
      console.log('Gamepad已连接:', event.gamepad.id)
      this.connectGamepad(event.gamepad.index)
    },
    
    onGamepadDisconnected(event) {
      console.log('Gamepad已断开:', event.gamepad.id)
      this.disconnectGamepad()
    },
    
    connectGamepad(index) {
      this.gamepadConnected = true
      this.gamepadIndex = index
      this.lastButtonStates = {}
      
      // 开始gamepad输入循环
      this.startGamepadLoop()
      
      console.log(`Gamepad ${index} 已连接并开始监听`)
    },
    
    disconnectGamepad() {
      this.gamepadConnected = false
      this.gamepadIndex = null
      
      // 停止gamepad输入循环
      if (this.gamepadAnimationFrame) {
        cancelAnimationFrame(this.gamepadAnimationFrame)
        this.gamepadAnimationFrame = null
      }
      
      // 移除事件监听器
      window.removeEventListener('gamepadconnected', this.onGamepadConnected)
      window.removeEventListener('gamepaddisconnected', this.onGamepadDisconnected)
      
      console.log('Gamepad已断开连接')
    },
    
    startGamepadLoop() {
      if (!this.gamepadConnected) return
      
      this.updateGamepad()
      this.gamepadAnimationFrame = requestAnimationFrame(() => this.startGamepadLoop())
    },
    
    updateGamepad() {
      if (!this.gamepadConnected || this.gamepadIndex === null) return
      
      const gamepads = navigator.getGamepads()
      const gamepad = gamepads[this.gamepadIndex]
      
      if (!gamepad) {
        this.disconnectGamepad()
        return
      }
      
      // 处理方向键/左摇杆输入
      this.handleGamepadMovement(gamepad)
      
      // 处理按钮输入
      this.handleGamepadButtons(gamepad)
    },
    
    handleGamepadMovement(gamepad) {
      if (this.gameOver || this.gamePaused) return
      
      // 左摇杆轴 (axes[0] = X轴, axes[1] = Y轴)
      const leftStickX = gamepad.axes[0] || 0
      const leftStickY = gamepad.axes[1] || 0
      
      // 方向键 (通常在axes[6]和axes[7]，或者buttons[12-15])
      const dpadX = gamepad.axes[6] || 0
      const dpadY = gamepad.axes[7] || 0
      
      // 合并摇杆和方向键输入
      let moveX = Math.abs(leftStickX) > this.deadZone ? leftStickX : dpadX
      let moveY = Math.abs(leftStickY) > this.deadZone ? leftStickY : dpadY
      
      // 处理移动
      if (Math.abs(moveX) > this.deadZone || Math.abs(moveY) > this.deadZone) {
        // 确定主要移动方向
        if (Math.abs(moveX) > Math.abs(moveY)) {
          // 水平移动
          if (moveX > this.deadZone) {
            this.move('right')
          } else if (moveX < -this.deadZone) {
            this.move('left')
          }
        } else {
          // 垂直移动
          if (moveY > this.deadZone) {
            this.move('backward')
          } else if (moveY < -this.deadZone) {
            this.move('forward')
          }
        }
      }
    },
    
    handleGamepadButtons(gamepad) {
      // 按钮映射 (标准gamepad布局)
      const buttons = {
        A: 0,      // A按钮 (Xbox) / X按钮 (PlayStation)
        B: 1,      // B按钮 (Xbox) / Circle按钮 (PlayStation)
        X: 2,      // X按钮 (Xbox) / Square按钮 (PlayStation)
        Y: 3,      // Y按钮 (Xbox) / Triangle按钮 (PlayStation)
        LB: 4,     // 左肩键
        RB: 5,     // 右肩键
        LT: 6,     // 左扳机
        RT: 7,     // 右扳机
        SELECT: 8, // Select/Back按钮
        START: 9,  // Start按钮
        LS: 10,    // 左摇杆按下
        RS: 11,    // 右摇杆按下
        UP: 12,    // 方向键上
        DOWN: 13,  // 方向键下
        LEFT: 14,  // 方向键左
        RIGHT: 15  // 方向键右
      }
      
      // 检查按钮按下事件 (只在按钮刚按下时触发)
      Object.entries(buttons).forEach(([name, index]) => {
        const button = gamepad.buttons[index]
        const isPressed = button && button.pressed
        const wasPressed = this.lastButtonStates[name] || false
        
        // 按钮刚按下时触发
        if (isPressed && !wasPressed) {
          this.handleGamepadButtonPress(name)
        }
        
        this.lastButtonStates[name] = isPressed
      })
    },
    
    handleGamepadButtonPress(buttonName) {
      switch (buttonName) {
        case 'A':
          // A按钮 - 开始/暂停游戏
          if (!this.gameStarted) {
            this.startGame()
          } else if (this.gamePaused) {
            this.resumeGame()
          } else {
            this.pauseGame()
          }
          break
          
        case 'B':
          // B按钮 - 停止移动
          this.stop()
          break
          
        case 'X':
          // X按钮 - 重新开始游戏
          if (this.gameOver) {
            this.restartGame()
          }
          break
          
        case 'Y':
          // Y按钮 - 返回首页
          this.goBack()
          break
          
        case 'START':
          // Start按钮 - 开始游戏
          if (!this.gameStarted) {
            this.startGame()
          }
          break
          
        case 'SELECT':
          // Select按钮 - 暂停/继续
          if (this.gameStarted) {
            if (this.gamePaused) {
              this.resumeGame()
            } else {
              this.pauseGame()
            }
          }
          break
          
        case 'UP':
          // 方向键上 - 前进
          this.move('forward')
          break
          
        case 'DOWN':
          // 方向键下 - 后退
          this.move('backward')
          break
          
        case 'LEFT':
          // 方向键左 - 左转
          this.move('left')
          break
          
        case 'RIGHT':
          // 方向键右 - 右转
          this.move('right')
          break
      }
    }
  },
  mounted() {
    this.initGamepad()
  },
  beforeUnmount() {
    this.stopTimer()
    this.disconnectGamepad()
  }
}
</script>

<style scoped>
.game-mode {
  width: 100%;
  height: 100vh;
  min-height: 100vh;
  background: linear-gradient(135deg, #fd79a8 0%, #e84393 100%);
  padding: 20px;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.back-btn {
  background: white;
  border: none;
  padding: 10px 20px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: #f1f2f6;
  transform: translateY(-2px);
}

.header h1 {
  color: white;
  font-size: 2.5rem;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.game-stats {
  display: flex;
  gap: 2rem;
  color: white;
  font-size: 1.2rem;
  font-weight: bold;
  flex-wrap: wrap;
}

.gamepad-status {
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.3s ease;
}

.gamepad-status.connected {
  color: #00b894;
  text-shadow: 0 0 10px rgba(0, 184, 148, 0.5);
}

.game-container {
  max-width: 1400px;
  margin: 0 auto;
}

.game-area {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 2rem;
}

.mission-panel, .control-panel {
  background: white;
  border-radius: 15px;
  padding: 1.5rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  height: fit-content;
}

.mission-panel h2, .control-panel h2 {
  color: #333;
  margin-bottom: 1rem;
  text-align: center;
}

.mission-title {
  font-size: 1.3rem;
  font-weight: bold;
  color: #e84393;
  margin-bottom: 0.5rem;
}

.mission-desc {
  color: #666;
  margin-bottom: 1rem;
}

.progress-bar {
  background: #f1f2f6;
  border-radius: 10px;
  height: 20px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  background: linear-gradient(90deg, #fd79a8, #e84393);
  height: 100%;
  transition: width 0.3s ease;
}

.progress-text {
  font-weight: bold;
  color: #e84393;
}

.game-map {
  background: white;
  border-radius: 15px;
  padding: 1rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  height: 500px;
}

.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, #f8f9fa 25%, transparent 25%), 
              linear-gradient(-45deg, #f8f9fa 25%, transparent 25%), 
              linear-gradient(45deg, transparent 75%, #f8f9fa 75%), 
              linear-gradient(-45deg, transparent 75%, #f8f9fa 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  border-radius: 10px;
  overflow: hidden;
}

.vehicle {
  position: absolute;
  font-size: 2rem;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
  z-index: 10;
}

.target {
  position: absolute;
  font-size: 1.5rem;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
}

.target.collected {
  opacity: 0.3;
  transform: translate(-50%, -50%) scale(0.5);
}

.obstacle {
  position: absolute;
  font-size: 1.5rem;
  transform: translate(-50%, -50%);
}

.direction-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 1rem;
}

.horizontal-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  background: #fd79a8;
  color: white;
  border: none;
  padding: 15px 20px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: bold;
  transition: all 0.3s ease;
  min-width: 60px;
}

.control-btn:hover:not(:disabled) {
  background: #e84393;
  transform: translateY(-2px);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.control-btn.stop {
  background: #e17055;
}

.control-btn.stop:hover:not(:disabled) {
  background: #d63031;
}

/* Gamepad控制样式 */
.gamepad-controls {
  background: rgba(0, 184, 148, 0.1);
  border: 2px solid rgba(0, 184, 148, 0.3);
  border-radius: 10px;
  padding: 1rem;
  margin-bottom: 1.5rem;
}

.gamepad-controls h3 {
  color: #00b894;
  margin: 0 0 1rem 0;
  text-align: center;
  font-size: 1.1rem;
}

.gamepad-instructions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.instruction-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.3rem 0;
  border-bottom: 1px solid rgba(0, 184, 148, 0.2);
}

.instruction-row:last-child {
  border-bottom: none;
}

.control-key {
  font-weight: bold;
  color: #00b894;
  font-size: 0.9rem;
}

.control-desc {
  color: #666;
  font-size: 0.9rem;
}

.game-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: bold;
  transition: all 0.3s ease;
}

.action-btn.start {
  background: #00b894;
  color: white;
}

.action-btn.pause {
  background: #fdcb6e;
  color: #333;
}

.action-btn.resume {
  background: #00b894;
  color: white;
}

.action-btn.restart {
  background: #e17055;
  color: white;
}

.action-btn:hover {
  transform: translateY(-2px);
}

.game-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.game-over-panel {
  background: white;
  padding: 3rem;
  border-radius: 20px;
  text-align: center;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.game-over-panel h2 {
  color: #333;
  font-size: 2rem;
  margin-bottom: 1rem;
}

.final-score, .final-level {
  font-size: 1.3rem;
  margin-bottom: 1rem;
  color: #666;
}

.restart-btn {
  background: #e84393;
  color: white;
  border: none;
  padding: 15px 30px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 1.2rem;
  font-weight: bold;
  transition: all 0.3s ease;
}

.restart-btn:hover {
  background: #d63384;
  transform: translateY(-2px);
}

@media (max-width: 1200px) {
  .game-area {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .game-map {
    height: 400px;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    text-align: center;
  }
  
  .header h1 {
    font-size: 1.8rem;
  }
  
  .game-stats {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .game-map {
    height: 300px;
  }
}
</style>